package com.canal.admin.util;

import com.google.common.hash.Hashing;

import java.nio.charset.StandardCharsets;

/**
 * 编码生成
 * @author yangbo
 * @date 2020-06-24 10:01
 */
public class CodeGenerator {

    private static final String CODE_64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    private CodeGenerator() {}

    /**
     * 生成渠道号编码
     * @param needHashStr
     * @return
     */
    public static String genCode(String needHashStr) {
        String hashStr = System.nanoTime() + "-" + needHashStr;
        long hashCode = Hashing.murmur3_32().hashString(hashStr, StandardCharsets.UTF_8).hashCode();
        hashCode = Math.abs(hashCode);
        return convertTo62(hashCode);
    }

    /**
     * 转化52进制
     * @param hashCode
     * @return
     */
    public static String convertTo62(long hashCode) {
        StringBuffer joiner = new StringBuffer();
        while (hashCode > 0) {
            char[] char64 = CODE_64.toCharArray();
            int mode = (int) (hashCode % char64.length);
            joiner.insert(0,char64[mode]);
            hashCode = hashCode / 62;
        }
        return joiner.toString();
    }
}
